// 跨域代理
const http = require("http");
const request = require("request");

const HOST_NAME = "127.0.0.1";
const PORT = 8010;
const IMG_POST = 8011;

// 创建一个API代理服务
const apiServer = http.createServer((req, res) => {
    const url = "http://news-at.zhihu.com/api/4" + req.url;
    const options = {
        url
    };
    function callback(error, response, body) {
        if (!error && response.statusCode === 200) {
            //设置编码类型,否则中文会乱码
            res.setHeader("Content-Type", "text/plain;charset=UTF-8");
            // 设置所有域允许跨域
            res.setHeader("Access-Control-Allow-Origin", "*");
            //返回代理后的内容
            res.end(body);
        }
    }
    request(options, callback);
})

// 创建一个图片代理服务
const imgServer = http.createServer((req, res) => {
    const url = req.url.split("/img")[1];
    const options = {
        url,
        encoding: null
    };
    function callback(error, response, body) {
        if (!error && response.statusCode === 200) {
            //设置编码类型,否则中文会乱码
            res.setHeader("Content-Type", "text/plain;charset=UTF-8");
            // 设置所有域允许跨域
            res.setHeader("Access-Control-Allow-Origin", "*");
            //返回代理后的内容
            res.end(body);
        }
    }
    request(options, callback);
})

apiServer.listen(PORT, HOST_NAME, () => {
    console.log(`接口代理运行在http://${HOST_NAME}:${PORT}`)
})

imgServer.listen(IMG_POST, HOST_NAME, () => {
    console.log(`图片代理运行在http://${HOST_NAME}:${IMG_POST}`)
})